# coding: utf-8
import base64
import hashlib
from pathlib import Path

import requests

from ..config import pytest_config
from ..logger import logger


class WeChatClient:
    """ Wechat 企业微信 """

    def __init__(self, webhook: str = None):
        if not webhook:
            webhook = pytest_config.wechat_setting.webhook
        self.webhook = webhook
        logger.debug(f"Wechat webhook: {webhook}")

    def post(self, data: dict):
        headers = {
            'Content-Type': 'application/json',
            'User-Agent': pytest_config.request_setting.user_agent
        }
        try:
            response = requests.post(url=self.webhook, json=data, headers=headers)
            response.raise_for_status()
            if response.json()['errcode'] != 0:
                logger.error(f"微信发送失败: {response.text}")
            else:
                logger.info(f"微信发送成功: {response.text}")
        except Exception as e:
            logger.error(f"微信发送失败: {e}")

    def send_text(self, content: str, mentioned_list: list = None, mentioned_mobile_list: list = None):
        """
        发送文本消息
        :param content:
        :param mentioned_list:
        :param mentioned_mobile_list:
        :return:
        """
        data = {
            "msgtype": "text",
            "text": {
                "content": content,
                "mentioned_list": mentioned_list or [],
                "mentioned_mobile_list": mentioned_mobile_list or []
            }
        }
        logger.debug(f"发送文本消息: {content}")
        self.post(data)

    def send_markdown(self, content: str):
        """
        发送 Markdown 消息
        :param content:
        :return:
        """
        data = {
            "msgtype": "markdown",
            "markdown": {
                "content": content
            }
        }
        logger.debug(f"发送 Markdown 消息: {content}")
        self.post(data)

    def send_image(self, fileName: str):
        """
        发送图片消息
        :param fileName:
        :return:
        """
        file = Path(fileName)
        if file.stat().st_size > 1024 * 1024 * 2:
            raise ValueError("图片大小不能超过 2MB")
        bfile = file.read_bytes()
        b64_data = str(base64.b64encode(bfile), "utf-8")
        # 计算文件 md5
        md5 = hashlib.md5()
        md5.update(bfile)
        fmd5 = md5.hexdigest()

        data = {
            "msgtype": "image",
            "image": {
                "base64": b64_data,
                "md5": fmd5
            }
        }
        self.post(data)
